package org.jeecg.modules.quartz.job;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.message.entity.SysMessageTemplate;
import org.jeecg.modules.message.service.ISysMessageTemplateService;
import org.jeecg.modules.system.service.ISysUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.CalendarUtil;
import cn.hutool.core.date.DateUtil;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.SalesDelivery;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.ISalesDeliveryService;
import io.finer.erp.jeecg.bas.service.IZrkPushSetService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;

public class CustomerAccountJob implements Job{
	@Autowired
	private IBasCustomerService customerService;
	@Autowired
	private ISalesDeliveryService deliveryService;
	@Autowired
	private ISysMessageTemplateService msgTemService;
	@Autowired
	private ISysBaseAPI sysBaseApi;
	@Autowired
	private IZrkPushSetService pushSetService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IZrkShoporderService zrkShoporderService;
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		List<BasCustomer> customerList = customerService.lambdaQuery().eq(BasCustomer::getIsEnabled, "1").list();
		if(CollUtil.isEmpty(customerList)) {
			return;
		}
		Date now = DateUtil.date();
		Integer zero = Integer.valueOf(0);
		List<String> stringList = Lists.newArrayList();
		Map<String, String> stringMap = Maps.newLinkedHashMap();
		for (BasCustomer customer : customerList) {
			String customerId = customer.getId();
			Integer zhangqi = customer.getZhangqi();
			if(null == zhangqi) {
				continue;
			}
			if(zhangqi.compareTo(zero) <= 0) {
				continue;
			}
			Calendar calendar = CalendarUtil.calendar(now);
			calendar.add(Calendar.DAY_OF_YEAR, 0 - zhangqi);
			Date accountDate = calendar.getTime();
			int count = this.deliveryService.lambdaQuery()
					.eq(SalesDelivery::getCustomerId, customerId)
					.ne(SalesDelivery::getHxType, "2")
					.eq(SalesDelivery::getSalesType, "0")
					.le(SalesDelivery::getCreateTime, accountDate)
					.count();
			if(0 == count) {
				continue;
			}
			List<SalesDelivery> list = this.deliveryService.lambdaQuery()
					.eq(SalesDelivery::getCustomerId, customerId)
					.ne(SalesDelivery::getHxType, "2")
					.eq(SalesDelivery::getSalesType, "0")
					.le(SalesDelivery::getCreateTime, accountDate).list();
			String customerResult = StringUtils.EMPTY;
			BigDecimal totalMoney = BigDecimal.ZERO;
			for (SalesDelivery delivery : list) {
				BigDecimal hxPrice = delivery.getHxPrice() == null ? BigDecimal.ZERO : delivery.getHxPrice();
				BigDecimal totalAmount = delivery.getTotalAmount() == null ? BigDecimal.ZERO : delivery.getTotalAmount();
				BigDecimal zkPrice = delivery.getZkPrice() == null ? BigDecimal.ZERO : delivery.getZkPrice();
				BigDecimal uPayMoney = totalAmount.subtract(hxPrice).subtract(zkPrice);
				totalMoney = totalMoney.add(uPayMoney);
			}
			StringBuffer resultBuffer = new StringBuffer(StringUtils.EMPTY);
			customerResult = resultBuffer.append("客户").append(customer.getName()).append("有").append(totalMoney.toPlainString()).append("的款项已到期，请处理。").toString();
			stringList.add(customerResult);
			stringMap.put(customerId, customerResult);
		}
		if(stringList.size() > 0) {
			List<SysMessageTemplate> templates = msgTemService.selectByCode("customer_account_temp");
			if(CollUtil.isEmpty(templates)) {
				return;
			}
			SysMessageTemplate template = templates.get(0);
			//发消息
			for(String key : stringMap.keySet()) {
				String result = stringMap.get(key);
				List<ZrkShoporder> list = zrkShoporderService.lambdaQuery().eq(ZrkShoporder::getCustomerId, key).last(" limit 1 ").orderByDesc(ZrkShoporder::getCreateTime).list();
				if(CollUtil.isEmpty(list)) {
					continue;
				}
				ZrkShoporder order = list.get(0);
				String userName = order.getCreateBy();
				sysBaseApi.sendSysAnnouncement("admin", userName, template.getTemplateName(), result);
			}
//			String result = CollUtil.join(stringList, ",");
			//发消息
//			String templateId = template.getId();
//			List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(templateId);
//			if(CollUtil.isEmpty(pushSetList)) {
//				return;
//			}
//			for (ZrkPushSet set : pushSetList) {
//				String userId = set.getUserId();
//				SysUser sysUser = sysUserService.getById(userId);
//				if(null == sysUser) {
//					continue;
//				}
//				if(StringUtils.isBlank(sysUser.getThirdId())) {
//					continue;
//				}
//				//发送系统消息
//				sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(), template.getTemplateName(), result);
//			}
		}
	}
}
